"""
Case Type   : security-check
Case Name   : 数据库$GPHOME目录及文件权限看护
Create At   : 2025/5/9
Owner       : wan005
Description :
    1.$GPHOME下目录权限700
    2.$GPHOME下目录权限不等于700数量统计
    3.$GPHOME下目录下的文件权限600
    4.$GPHOME下目录下的文件权限不等于600数量统计
Expect      :
    1.检查成功
    2.数目为0
    3.检查成功
    4.数目为0
History     :
"""
import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger


class Security(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'---{os.path.basename(__file__)} start---')
        self.userNode = Node(node='PrimaryDbUser')

    def test_encrypted(self):
        text = '---pre1:获取$GPHOME路径;expect:检查成功---'
        self.logger.info(text)
        pre_cmd = f'source {macro.DB_ENV_PATH};echo $GPHOME'
        dir_path = self.userNode.sh(pre_cmd).result()
        self.logger.info(dir_path)

        text = '---step1:$GPHOME下目录权限不等于700数量统计;expect:数目为0---'
        self.logger.info(text)
        cmd1 = f"ls -lR {dir_path}| grep '^d' | grep -v 'drwx------'"
        res1 = self.userNode.sh(cmd1).result()
        self.logger.info(res1)
        self.assertEqual('', res1, text + '执行失败')

        text = '---step2:$GPHOME下目录权限700;expect:成功---'
        self.logger.info(text)
        cmd2 = f"ls -lR {dir_path}| grep '^d' | grep -v 'drwx------'|wc -l"
        res2 = self.userNode.sh(cmd2).result()
        self.logger.info(res2)
        self.assertEqual('0', res2, text + '执行失败')

        text = '---step3:$GPHOME下目录下的文件权限600;expect:检查成功---'
        self.logger.info(text)
        cmd3 = f"ls -lR {dir_path} |grep '^\-' |grep -v '\-rwx------' |grep " \
               f"-v '\-rw-------' |grep -v '\-r--------'"
        self.logger.info(cmd3)
        res3 = self.userNode.sh(cmd3).result()
        self.logger.info(res3)
        res3_list = ['gs_check', 'gs_checkperf', 'gs_checkse', 'gs_collector',
                     'gs_ddr', 'gs_dropnode', 'gs_expansion', 'gs_install',
                     'gs_upgradectl', 'gs_perfconfig', 'gs_sdr', 'gs_ssh',
                     'gs_sshexkey', 'gs_uninstall', 'gs_upgradechk','gs_om']
        for item in res3_list:
            self.assertIn(item, res3, '执行失败' + text)

        text = '---step4:$GPHOME下目录下的文件权限不等于600数量统计;expect:数目为0---'
        self.logger.info(text)
        cmd4 = f"ls -lR {dir_path}| grep '^\-' |grep -v '\-rwx------'|grep " \
               f"-v '\-rw-------' |grep -v '\-r--------'|wc -l"
        self.logger.info(cmd4)
        res4 = self.userNode.sh(cmd4).result()
        self.logger.info(res4)
        self.assertEqual('17', res4, text + '执行失败')

    def tearDown(self):
        self.logger.info(f'---{os.path.basename(__file__)} start---')
